/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
        /*
        if (pHead1 == null || pHead2 == null) {
            return null;
        }
        while (pHead1 != null) {
            pHead1.val += 1000; 
            pHead1 = pHead1.next;
        }
        while (pHead2 != null) {
            if (pHead2.val > 1000) {
                break;
            }
            else {
                pHead2 = pHead2.next;
            }
        }
        ListNode ret = pHead2;
        while (pHead2 != null) {
            pHead2.val -= 1000;
            pHead2 = pHead2.next;
        }
        return ret;
        */

        // 后部分完全相同
        // 栈
        // set
        // 差值法
        // 等值法
        ListNode a = pHead1, b = pHead2;
        while (a != b) {
            a = a == null ? pHead2 : a.next;
            b = b == null ? pHead1 : b.next;
        }
        return a;
    }
}
